<?php

namespace app\admin\controller;

use app\base\model\File;
use app\common\controller\AdminBase;
use think\Request;
use think\Config;
use PHPExcel_Reader_Excel2007;
use PHPExcel_Reader_Excel5;
use PHPExcel_Shared_Date;
use PHPExcel_RichText_Run;
use PHPExcel_RichText;

class Question extends AdminBase {
  protected $model;

  public function __construct(Request $request = NULL) {
    parent::__construct($request);
    $this->model = new \app\admin\model\Question();
  }

  public function _initialize() {
    parent::_initialize();
  }

  public function index() {
    $page = input('page/d', 1, 'abs');
    $search = input('search/a', NULL);
    $map = [];
    if (is_array($search)) {
      if ($search['type'] >= 0) {
        $map['type'] = $search['type'];
      }
      if ($search['content']) {
        $map['content'] = ['like',
                           '%' . $search['content'] . '%'];
      }
    }
    $rows = $this->model
      ->alias('q')
      ->join('__BASE_USER__ u', 'u.id=q.creator_uid', 'left')
      ->where($map)
      ->order('q.id DESC')
      ->field('u.realname,q.content,q.create_time,q.id,q.type,q.creator_uid,q.disable')
      ->paginate(config('paginate')['list_rows'], FALSE, ($search ? ['query' => ['search' => $search]] : []));
    $qType = config('question')['type'];

    return view('', [
      'rows'   => $rows,
      'page'   => $page,
      'search' => $search,
      'qType'  => [-1 => '所有'] + $qType]);
  }

  public function add() {
    return self::edit();
  }

  public function edit() {
    $id = input('id/d', 0, 'abs');
    if (!request()->isPost()) {
      $row = ($id > 0) ? $this->model->find($id) : [];
      $qType = Config::get('question.type');

      return view('edit', [
        'row'     => $row,
        'qType'   => $qType,
        'answers' => $row ? $row['answers'] : json_encode([]),
        'right'   => $row ? $row['right'] : -1,
      ]);
    }
    $form = input('form/a', NULL);

    $form['answers'] = json_encode($form['answer']);
    $result = $this->validate($form, 'Question');
    if (TRUE !== $result) {
      $this->error($result);
    }
    cmf_log('修改问题', $id, $form);
    $this->model->editJump($form, $id, url('index'));
  }

  /**
   * 导入excel文件
   */
  public function import() {
    $fileId = input('file_id/d', 0, 'abs');
    if (!$fileId) {
      return view();
    }
    $modelFile = new File();
    $fileInfo = $modelFile->getFile($fileId);
    $filename = url('/public/' . $fileInfo['filepath'], NULL, '');
    $filename = realpath("../") . $filename;

    $objPHPExcelReader = new PHPExcel_Reader_Excel2007();
    if (!$objPHPExcelReader->canRead($filename)) {
      $objPHPExcelReader = new PHPExcel_Reader_Excel5();
      if (!$objPHPExcelReader->canRead($filename)) {
        $this->error('当前EXCEL文档的格式错误。');
      }
    }
    $PHPExcel = $objPHPExcelReader->load($filename);
    $sheet = $PHPExcel->getSheet(0);
    $qData = [];
    foreach ($sheet->getRowIterator() as $k1 => $row) {
      if ($row->getRowIndex() < 2) continue; //跳过首行
      foreach ($row->getCellIterator() as $k2 => $cell) {
        $value = $cell->getValue();
        if ($value instanceof PHPExcel_RichText) { //富文本转换字符串
          $value = $value->__toString();
        }
        if($value=='') continue;
        switch ($k2) {
          case 'A':
            $qData[ $k1 ]['type'] = ($value == '判断题') ? 0 : 1;
            break;
          case 'B':
            $qData[ $k1 ]['content'] = $value;
            break;
          case 'C':
            $arr = explode('|', $value);
            $qData[ $k1 ]['answers'] = json_encode($arr);
            break;
          case 'D':
            $value = strtoupper($value); //答案转大写
            $ord = ord($value); //答案转ascii码
            $qData[ $k1 ]['right'] = $ord - 65; //答案转数字
            break;
          default:
            break;
        }
        $qData[ $k1 ]['creator_uid'] = $this->uid;
      }
    }


    try {
      $r = $this->model->saveAll($qData);
    } catch (\Exception $e) {
      $this->error(lang('error') . $this->model->getError() . $e->getMessage());
    }
    cmf_log('批量导入问题', 0, $r);
    $this->success(lang('success'), 'index');
  }


  public function disable() {
    $id = input('id/d', 0, 'abs');
    $row = $this->model->find($id);
    if (!$row) $this->error(lang('data empty'));
    $data = ['disable' => !$row['disable']];
    $r = $this->model->save($data, ['id' => $id]);
    if ($r !== FALSE) {
      cmf_log('禁用/启用问题', $id);
      $this->success(lang('success'));
    }

    $this->error(lang('error'));
  }


}